﻿#include "system_time_ctl.hpp"
#include <iostream>
#include <chrono>
#include <ctime>

#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#include <unistd.h>
#endif

cpp::Result<> SystemTimeCtl::syncTime(const std::string& ntpServer)
{
    try
    {
#if defined(_WIN32)
        return cpp::Result<>::Err("No support platform.");
        // // Windows 使用 w32tm 命令同步时间
        // std::string cmd = "w32tm /resync /nowait";
        // int result = system(cmd.c_str());
#else
        // Linux 使用 ntpdate 命令同步时间
        std::string cmd = "ntpd " + ntpServer;
        int32_t result = system(cmd.c_str());
        if (result == 0)
        {
            return cpp::Result<>::Ok();
        }
        else
        {
            return cpp::Result<>::Err("Set System Time error.");
        }
#endif
    }
    catch (const std::exception& e)
    {
        return cpp::Result<>::Err(e.what());
    }
}

cpp::Result<> SystemTimeCtl::setTime(uint64_t timestamp)
{
    try
    {
        // 转换为秒和微秒
        time_t seconds = timestamp / 1000;
        long microseconds = (timestamp % 1000) * 1000;

#if defined(_WIN32)
        // 将秒转换为 tm 结构
        struct tm* timeinfo;
        timeinfo = gmtime(&seconds);
        if (!timeinfo)
        {
            std::cerr << "time error。" << std::endl;
            return cpp::Result<>::Err("TIme transform error");
        }

        // 填充 SYSTEMTIME 结构
        SYSTEMTIME st;
        st.wYear = timeinfo->tm_year + 1900;
        st.wMonth = timeinfo->tm_mon + 1;
        st.wDay = timeinfo->tm_mday;
        st.wHour = timeinfo->tm_hour;
        st.wMinute = timeinfo->tm_min;
        st.wSecond = timeinfo->tm_sec;
        st.wMilliseconds = microseconds / 1000;

        if (SetSystemTime(&st))
        {
            return cpp::Result<>::Ok();
        }
        else
        {
            return cpp::Result<>::Err("time set error");
        }
#else
        // Linux 使用 settimeofday 设置时间
        struct timeval tv;
        tv.tv_sec = seconds;
        tv.tv_usec = microseconds;

        if (settimeofday(&tv, nullptr) == 0)
        {
            return cpp::Result<>::Ok();
        }
        else
        {
            return cpp::Result<>::Err("time set error");
        }
#endif
    }
    catch (const std::exception& e)
    {
        return cpp::Result<>::Err(e.what());
    }
}

uint64_t SystemTimeCtl::getCurrentTime()
{
    // 获取当前时间（毫秒时间戳）
    auto now = std::chrono::system_clock::now();
    auto duration = now.time_since_epoch();
    return std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
}
